package ans.p129;

import ans.base.TreeNode;
import test.Entrance;

/**
 * #      129
 * 名称   求根节点到叶节点数字之和
 * 链接   https://leetcode-cn.com/problems/sum-root-to-leaf-numbers
 * 题解   [877](https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/solution)
 * 通过率 66.9%
 * 难道   中等
 */

public class Solution {
    @Entrance
    public int sumNumbers(TreeNode root) {
        int[] ans = new int[]{0, 0};
        if (root != null) {
            ans[1] = root.val;
            traceback(ans, root);
        }
        return ans[0];
    }

    public void traceback(int[] ans, TreeNode root) {
        if (root.right == null && root.left == null) {
            ans[0] += ans[1];
        }
        if (root.left != null) {
            ans[1] = ans[1] * 10 + root.left.val;
            traceback(ans, root.left);
            ans[1] = (ans[1] - root.left.val) / 10;
        }
        if (root.right != null) {
            ans[1] = ans[1] * 10 + root.right.val;
            traceback(ans, root.right);
            ans[1] = (ans[1] - root.right.val) / 10;
        }
    }

}